<template>
  <div class="app-container">
    <el-card class="product-card">
      <el-form ref="productForm" :model="form" label-width="80px">
        <el-form-item label="产品名" prop="product_name">
          <el-input v-model="form.product_name" placeholder="这里输入产品名" @keyup.enter.native="createProduct" />
        </el-form-item>
        <el-button type="primary" @click="createProduct">创建</el-button>
      </el-form>
    </el-card>

    <el-card class="product-list-card">
      <el-table :data="productList" border style="width: 100%" :default-sort="{ prop: 'created_at', order: 'descending' }"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="产品名称" />
        <el-table-column prop="activation_count" label="激活次数" width="100" />
        <el-table-column prop="key_count" label="密钥数量" width="100" />
        <el-table-column prop="created_at" label="创建时间" sortable :sort-method="sortCreatedAt" />
        <el-table-column label="API ID">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="copyApiId(row)">复制</el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button type="danger" size="small" @click="openDeleteDialog(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>


      <el-button type="danger" class="batch-delete-btn" :disabled="selectedProducts.length === 0"
        @click="openBatchDeleteDialog">
        批量删除
      </el-button>
    </el-card>

    <!-- Individual Delete Confirmation Dialog -->
    <el-dialog title="确认删除" :visible.sync="deleteDialogVisible" width="30%" @close="resetDeleteData">
      <span>确定要删除该产品吗?</span>
      <p>如果你这样做了，将会同时删除该产品下所有相关的密钥!</p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetDeleteData">取消</el-button>
        <el-button type="danger" @click="confirmDelete">确定删除</el-button>
      </span>
    </el-dialog>

    <!-- Batch Delete Confirmation Dialog -->
    <el-dialog title="确认批量删除" :visible.sync="batchDeleteDialogVisible" width="30%" @close="resetBatchDeleteData">
      <span>确定要删除选中的所有产品吗?</span>
      <p>如果你这样做了，将会同时删除该产品下所有相关的密钥!</p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetBatchDeleteData">取消</el-button>
        <el-button type="danger" @click="confirmBatchDelete">确定删除</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { createProduct, getProductList, deleteProduct } from '@/api/product'

export default {
  name: 'ProductManager',
  data() {
    return {
      form: {
        product_name: ''
      },
      productList: [],
      selectedProducts: [],
      deleteDialogVisible: false,
      batchDeleteDialogVisible: false,
      productToDelete: null
    }
  },
  mounted() {
    this.fetchProducts()
  },
  methods: {
    fetchProducts() {
      getProductList(-1)
        .then(response => {
          this.productList = response.data.products.map(product => ({
            ...product,
            customApiId: product.api_id,
            activation_count: product.activation_count,
            key_count: product.key_count
          }))
        })
        .catch(() => {
          this.$message.error('获取产品列表失败')
        })
    },

    createProduct() {
      if (!this.form.product_name.trim()) {
        this.$message.error('请输入产品名')
        return
      }
      createProduct({ name: this.form.product_name })
        .then(() => {
          this.$message.success('产品创建成功')
          this.fetchProducts()
        })
        .catch(() => {
          this.$message.error('创建失败')
        })
    },
    handleSelectionChange(selection) {
      this.selectedProducts = selection.map(item => item.id)
    },
    openDeleteDialog(row) {
      this.productToDelete = row.id
      this.deleteDialogVisible = true
    },
    resetDeleteData() {
      this.deleteDialogVisible = false
      this.productToDelete = null
    },
    confirmDelete() {
      if (this.productToDelete) {
        deleteProduct([this.productToDelete]) // Call the API function, not the local method
          .then(() => {
            this.$message.success('删除成功')
            this.fetchProducts()
            this.resetDeleteData()
          })
          .catch(() => {
            this.$message.error('删除失败')
          })
      }
    },
    openBatchDeleteDialog() {
      if (this.selectedProducts.length === 0) {
        this.$message.error('请选择至少一个产品')
        return
      }
      this.batchDeleteDialogVisible = true
    },
    resetBatchDeleteData() {
      this.batchDeleteDialogVisible = false
    },
    confirmBatchDelete() {
      if (this.selectedProducts.length > 0) {
        deleteProduct(this.selectedProducts)
          .then(() => {
            this.$message.success('批量删除成功')
            this.fetchProducts()
            this.resetBatchDeleteData()
          })
          .catch(() => {
            this.$message.error('批量删除失败')
          })
      }
    },
    batchDelete() {
      // This method is now no longer needed since we handle batch delete with the dialog
    },
    sortCreatedAt(a, b) {
      const dateA = new Date(a.created_at)
      const dateB = new Date(b.created_at)
      return dateA - dateB
    },
    copyApiId(row) {
      if (row && row.customApiId) {
        navigator.clipboard.writeText(row.customApiId)
          .then(() => {
            this.$message.success('API ID 已复制到剪贴板')
          })
          .catch(() => {
            this.$message.error('复制失败')
          })
      } else {
        this.$message.error('无法找到API ID')
      }
    }
  }
}
</script>

<style scoped>
.product-card {
  width: 400px;
  margin: 20px auto;
  padding: 20px;
}

.product-list-card {
  width: 100%;
  margin: 20px auto;
  padding: 10px;
}

.batch-delete-btn {
  margin-top: 20px;
}
</style>
